<template>
    <el-table :data="processedTableData" style="width: 100%" border :span-method="handleSpanMethod">
      <!-- 主表信息列 -->
      <el-table-column prop="pb_code" label="出库单号" width="180" />
      <el-table-column prop="po_name" label="采购单名称" width="180" />
      <el-table-column prop="vendor_name" label="供应商" width="150" />
      <el-table-column prop="contacts_name" label="联系人" width="120" />
      <el-table-column prop="contacts_phone" label="联系电话" width="130" />
      
      <!-- 商品详情列 -->
      <el-table-column prop="pro_name" label="商品名称" width="150" />
      <el-table-column prop="pro_code" label="商品编码" width="150" />
      <el-table-column prop="pro_brand" label="品牌" width="120" />
      <el-table-column prop="pro_model" label="型号" width="120" />
      <el-table-column prop="details_monovalent" label="单价" width="100" align="right">
        <template #default="{ row }">
          {{ row.details_monovalent?.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="po_number" label="采购数量" width="100" align="right" />
      <el-table-column prop="details_storage" label="入库数量" width="100" align="right" />
      
      <!-- 状态和时间列 -->
      <el-table-column prop="po_state" label="状态" width="120">
        <template #default="{ row }">
          {{ formatState(row.po_state) }}
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.create_time) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      @current-change="fetchData"
      layout="prev, pager, next"
    /> -->
    <div class="pagination-wrapper">
            <el-pagination 
                v-model:current-page="currentPage" 
                v-model:page-size="pageSize" 
                :page-sizes="[5, 10, 20, 50]"
                :background="true" 
                layout="total, sizes, prev, pager, next, jumper" 
                :total="pageCount"
                @size-change="handleSizeChange" 
                @current-change="handleCurrentChange" 
            />
        </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const props = defineProps({
  code: {
    type: String,
    required: true
  }
})

// 原始数据和分页
const rawData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const pageCount = ref(0)

// 处理后的表格数据（展开details）
const processedTableData = computed(() => {
  const result = []
  rawData.value.forEach(item => {
    if (item.details && item.details.length > 0) {
      item.details.forEach((detail, index) => {
        result.push({
          ...item,
          ...detail,
          // 标记这是第几个detail，用于合并单元格
          _detailIndex: index,
          _detailCount: item.details.length
        })
      })
    } else {
      result.push({
        ...item,
        _detailIndex: 0,
        _detailCount: 1
      })
    }
  })
  return result
})

// 合并单元格方法
const handleSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 需要合并的列（主表信息）
  const mergeColumns = ['pb_code', 'po_name', 'vendor_name', 'contacts_name', 'contacts_phone']
  
  if (mergeColumns.includes(column.property)) {
    if (row._detailIndex === 0) {
      return {
        rowspan: row._detailCount,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}
function handleSizeChange(){

}
function handleCurrentChange(){

}
function count(){
  axios.get('http://localhost:5181/api/Pb/GetPbCount',{
    params:{
      Pb_code:props.code,
    },
    headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
                }
  }).then((result) => {
    pageCount.value = result.data;
  }).catch((err) => {
    console.error('总条数加载失败', err);
  });
}

// 状态格式化
const formatState = (state) => {
  const states = {
    0: '待入库',
    1: '未知',
    2: '部分入库',
    3: '已完成'
  }
  return states[state] || '未知状态'
}

// 时间格式化
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://localhost:5181/api/Pb/GetPbFyWhereinfo', {
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        Pb_code: props.code
      }
    })
    
    rawData.value = response.data || []
    total.value = response.data?.length || 0
  } catch (error) {
    ElMessage.error('获取出库记录失败: ' + error.message)
    console.error('API 错误:', error)
  } finally {
    loading.value = false
  }
}

// 监听 code 变化
watch(() => props.code, (newCode) => {
  if (newCode) {
    currentPage.value = 1
    fetchData()
    count()
  }
}, { immediate: true })
</script>

<style scoped>


.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>